package com.es;

import java.io.IOException;
import java.sql.SQLException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;
import com.es.db.indexdb.dao.Obj2CloumnDao;
import com.es.db.indexdb.dao.PriceDao;
import com.es.db.indexdb.dao.ProductDao;
import com.es.db.indexdb.dao.SellAmountDao;
import com.es.db.indexdb.dao.impl.Obj2CloumnDaoImpl;
import com.es.db.indexdb.dao.impl.PriceDaoImpl;
import com.es.db.indexdb.dao.impl.ProductDaoImpl;
import com.es.db.indexdb.dao.impl.SellAmountDaoImpl;
import com.es.db.indexdb.service.ProductService;
import com.es.index.product.ProductIndexHandler;

@Configuration
@PropertySource(value = {"classpath:application.properties","classpath:jdbc.properties"}, ignoreResourceNotFound = true, encoding = "utf-8")
public class AppConfig {
	
	@Autowired
	private Environment env;
    
  //  @Bean("productIndex")
    public ProductIndexHandler getGoodsIndex(){
    	return ProductIndexHandler.getInstance();
    }
    
    @Bean("productService")
    public ProductService getProductService(){
    	return new ProductService();
    }
    
    @Bean("productDao")
    public ProductDao getProductDao(){
    	return new ProductDaoImpl();
    }
    @Bean("priceDao")
    public PriceDao getPriceDao(){
    	return new PriceDaoImpl();
    }
    
    @Bean("obj2CloumnDao")
    public Obj2CloumnDao getObj2CloumnDao(){
    	return new Obj2CloumnDaoImpl();
    }
    
    @Bean("sellAmountDao")
    public SellAmountDao getSellAmountDao(){
    	return new SellAmountDaoImpl();
    }

    @Bean(name="indexDBTemplate")
    public JdbcTemplate indexDBTemplate() throws SQLException{
    	JdbcTemplate template = new JdbcTemplate(indexDBSource());
    	return template;
    }
    
    public DataSource indexDBSource() throws SQLException {
        DruidDataSource druid = new DruidDataSource();
        druid.setName("indexDB");
        druid.setUsername(env.getProperty("jdbc.index.username"));
        druid.setPassword(env.getProperty("jdbc.index.password"));
        druid.setUrl(env.getProperty("jdbc.index.url"));
        druid.setDriverClassName(env.getProperty("jdbc.index.driver"));
       //初始连接数
        druid.setInitialSize(10);
        //最小连接数
        druid.setMinIdle(10);
        //最大连接数
       druid.setMaxActive(100);
       //最大等待时间 10s
        druid.setMaxWait(10000);
        //配置隔多久进行一次检测，检测需要关闭的空闲连接 1分钟
        druid.setTimeBetweenEvictionRunsMillis(60000);
        //一个连接的最小生存时间 5分钟
        druid.setMinEvictableIdleTimeMillis(300000);
        //建议配置为true，不影响性能，并且保证安全性。
        //申请连接的时候检测，如果空闲时间大于timeBetweenEvictionRunsMillis，
        //执行validationQuery检测连接是否有效。
        druid.setTestWhileIdle(true);
        //建议配置为true，防止去到的连接不可用
        druid.setTestOnBorrow(true);
        druid.setTestOnReturn(true);
        //是否缓存preparedStatement，也就是PSCache。
        //PSCache对支持游标的数据库性能提升巨大，比如说oracle。在mysql下建议关闭。
       // druid.setPoolPreparedStatements(false);
        //druid.setMaxPoolPreparedStatementPerConnectionSize(20);
        
        //配置提交方式，默认true 可以不配置
        druid.setDefaultAutoCommit(true);
        //验证连接有效与否的sql，不同的数据配置不同
        druid.setValidationQuery("select 1");
        //属性类型是字符串，通过别名的方式配置扩展插件，常用的插件有： 
        //监控统计用的filter:stat日志用的filter:log4j防御sql注入的filter:wall
        druid.setFilters("stat,wall,log4j");
        return druid;
    }
    @Bean(name="indexDBTransactionManager")
    public DataSourceTransactionManager transactionManager() throws SQLException{
    	DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
    	transactionManager.setDataSource(indexDBSource());
    	return transactionManager;
    }
    public static void main(String[] args) throws IOException {
    	//加载配置
        @SuppressWarnings("resource")
		final
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
        //ctx.start();
     /* ProductIndexHandler handler = ctx.getBean("productIndex", ProductIndexHandler.class);
      handler.create(1, 4000);*/
        ExecutorService service = Executors.newFixedThreadPool(100);
        for (int i = 1; i <= 100; i ++) {
			service.execute(new Runnable() {
				
				public void run() {
					SellAmountDao sellAmountDao = ctx.getBean("sellAmountDao",SellAmountDao.class);
					int row = sellAmountDao.update(56, 1);
					if (row > 0) {
						System.out.println("成功");
					}else {
						System.out.println("失败");
					}
				}
			});
		}
        
	}

}
